package com.dream.house.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dream.house.utils.Constants;

/**
 * 
 * @author ahk
 * @since 1.0
 */
public class LoginFilter implements Filter {
 
    public static String loginUrl="/gotoLogin.htm";
    protected FilterConfig config;

    public void init(FilterConfig config) throws ServletException {
    	this.config=config;
//    	loginUrl=config.getInitParameter(loginUrl);
    }

    public void doFilter(ServletRequest servletRequest, 
    		ServletResponse servletResponse, FilterChain filterChain)
                    throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUri = request.getRequestURI();

        // 如果请求的不是登录界面
        if (!requestUri.endsWith("index.htm") && !requestUri.endsWith("login.htm")) {
            // 未登录,跳转到重登录页面
            if (request.getSession().getAttribute(Constants.CURRENT_USER) == null) {
            	request.getSession().getServletContext().getRequestDispatcher(loginUrl).forward(request, response);
                return;
            }
            
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy() {
    }
}
